//
//  LXLMultiPhotoCollectionViewController.m
//  FZAH
//
//  Created by 李小龙 on 17/3/24.
//  Copyright © 2017年 zdqk. All rights reserved.
//

#import "LXLMultiPhotoCollectionViewController.h"
#import "LXLMultiPhotoCollectionViewCell.h"
#import "LXLChooseImageModel.h"

@interface LXLMultiPhotoCollectionViewController ()
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *backButton;

@property (nonatomic, strong) NSMutableArray *chooseArray;// 带NULL的 做选中标记的数组
@property (nonatomic, strong) NSMutableArray *assetsArray;// 全部原始资源的数组
@property (nonatomic, strong) NSMutableArray *imageArray; // 高清缩略图的数组

@property (nonatomic, strong) NSMutableArray *resultArr; // 最终选择的图片数组

@end

@implementation LXLMultiPhotoCollectionViewController

static NSString * const reuseIdentifier = @"Cell";
- (IBAction)doneButtonAction:(id)sender {
    if (self.resultblock) {
        self.resultblock(self.resultArr);
    }
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)backButtonAction:(id)sender {
    //self.presentingViewController.view.alpha = 0.0f;
    //NSLog(@"%@",self.chooseArray);
    //    LXLChooseImageModel *chooseModel = [LXLChooseImageModel shareInstance];
    //    [chooseModel.chooseImageArr removeAllObjects];
    //    for (ALAsset *asset in self.chooseArray) {
    //        if ([asset isKindOfClass:[ALAsset class]]) {
    //            [chooseModel.chooseImageArr addObject:asset];
    //        }
    //    }
    
    [[LXLChooseImageModel shareInstance].chooseImageArr removeAllObjects];
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        //self.collection = nil;
    }
    return self;
}
- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc] init];
    }
    return _imageArray;
}
- (NSMutableArray *)assetsArray {
    if (!_assetsArray) {
        _assetsArray = [[NSMutableArray alloc] init];
    }
    return _assetsArray;
}
- (NSMutableArray *)chooseArray {
    if (!_chooseArray) {
        _chooseArray = [[NSMutableArray alloc] init];
    }
    return _chooseArray;
}

- (NSMutableArray *)resultArr {
    if (!_resultArr) {
        _resultArr = [NSMutableArray array];
    }
    return _resultArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Register cell classes
    [self.titleLabel setText:_collection.localizedTitle];
    
    // Do any additional setup after loading the view.
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"LXLMultiPhotoCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];
    
}

- (void)setCollection:(PHAssetCollection *)collection {
    _collection = collection;
    [self.assetsArray removeAllObjects];
    [self.chooseArray removeAllObjects];
    [self enumerateAssetsInAssetCollection:self.collection];
}
/**
 *  遍历相簿中的所有图片
 *  @param assetCollection 相簿
 */
- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection {
    NSLog(@"相簿名:%@", assetCollection.localizedTitle);
    // 获得某个相簿中的所有PHAsset对象
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
    for (PHAsset *asset in assets) {
        [self.assetsArray insertObject:asset atIndex:0];
        [self.chooseArray addObject:[NSNull null]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.assetsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LXLMultiPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // Configure the cell
    PHAsset *asset = self.assetsArray[indexPath.row];
    CGSize size = CGSizeMake(cell.photoImage.width*2, cell.photoImage.height*2);
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = NO;
    // 从asset中获得图片
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.photoImage setImage:result];
        });
    }];
    
    
    if (![self.chooseArray[indexPath.row] isKindOfClass:[NSNull class]]) {
        [cell.selectButton setSelected:YES
         ];
    } else {
        [cell.selectButton setSelected:NO];
    }
    [cell.selectButton setTag:indexPath.row+100];
    [cell.selectButton addTarget:self action:@selector(selectImageAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)selectImageAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
    id temp;
    if (button.selected) {
        if (self.selectNum < self.maxNum) {
            temp = self.assetsArray[button.tag-100];
            [[LXLChooseImageModel shareInstance].chooseImageArr addObject:temp];
            [self.resultArr addObject:temp];
            self.selectNum++;
        } else {
            [self showAlertMessage:[NSString stringWithFormat:@"最多添加%ld张图片",_maxNum]];
            [button setSelected:NO];
            return;
        }
        
    } else {
        [[LXLChooseImageModel shareInstance].chooseImageArr removeObject:self.assetsArray[button.tag-100]];
        [self.resultArr removeObject:self.assetsArray[button.tag-100]];
        temp = [NSNull null];
        self.selectNum--;
    }
    [self.chooseArray replaceObjectAtIndex:(button.tag-100) withObject:temp];
    
}

//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    CGFloat itemW = (screenWidth - 9.0*5) / 4;
//    return CGSizeMake(itemW, itemW);
//}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LXLMultiPhotoCollectionViewCell *cell = (LXLMultiPhotoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    PHAsset *asset = self.assetsArray[indexPath.row];
    CGSize size = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    // 从asset中获得图片
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showPicture:cell.photoImage image:result];
        });
    }];
    
}
- (void)showPicture:(UIView *)view image:(UIImage *)image {
    IDMPhoto *photo = [[IDMPhoto alloc] initWithImage:image];
    IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotos:@[photo] animatedFromView:view];
    browser.displayActionButton = NO;
    browser.displayArrowButton = NO;
    browser.displayCounterLabel = NO;
    browser.displayDoneButton = NO;
    browser.doneButtonImage = [UIImage imageNamed:@"out"];
    if ([view isKindOfClass:[UIImageView class]]) {
        UIImageView *imageView = (UIImageView *)view;
        browser.scaleImage = imageView.image;
    }
    browser.dismissOnTouch = YES;
    [self presentViewController:browser animated:YES completion:nil];
}
- (void)showPicture:(UIView *)view index:(NSInteger)index urls:(NSArray *)urls{
    NSMutableArray *urlArr = [NSMutableArray array];
    for (NSString *imgUrl in urls) {
        NSURL *url = [NSURL URLWithString:imgUrl];
        [urlArr addObject:url];
    }
    //IDMPhoto *photo = [IDMPhoto photoWithURL:[NSURL URLWithString:imgUrl]];
    
    IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotoURLs:urlArr animatedFromView:view];
    //IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotos:@[photo] animatedFromView:self.imageView];
    browser.displayActionButton = NO;
    browser.displayArrowButton = NO;
    browser.displayCounterLabel = NO;
    browser.displayDoneButton = NO;
    browser.doneButtonImage = [UIImage imageNamed:@"out"];
    if ([view isKindOfClass:[UIImageView class]]) {
        UIImageView *imageView = (UIImageView *)view;
        browser.scaleImage = imageView.image;
    }
    browser.dismissOnTouch = YES;
    [browser setInitialPageIndex:index];
    [self presentViewController:browser animated:YES completion:nil];
}
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

- (void)showAlertMessage:(NSString *)message {
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertC addAction:action];
    [self presentViewController:alertC animated:YES completion:nil];
}


@end
